<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=6.7.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.7.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon32.ico?v=6.7.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon16.ico?v=6.7.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.7.0" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.7.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="MySql数据库的基本操作 MySql是关系型数据，关系型数据库是基于关系模型的数据库，而关系模型是通过二维表来保存的，所以它的存储方式就是行列组成的表，每一列是一个字段，每一行是一条记录。在Python2中连接MySql的库大多是MySQLdb，但是这个库在Python3中不在支持，所以这里我推荐是PyMySQL。相信PyMySQL的安装大家都懂，只需要pip install pymysql下载">
<meta name="keywords" content="MySql,Python">
<meta property="og:type" content="article">
<meta property="og:title" content="MySql数据库操作">
<meta property="og:url" content="http://yoursite.com/2018/12/07/MySql数据库操作/index.html">
<meta property="og:site_name" content="LF&#39;s Blogs">
<meta property="og:description" content="MySql数据库的基本操作 MySql是关系型数据，关系型数据库是基于关系模型的数据库，而关系模型是通过二维表来保存的，所以它的存储方式就是行列组成的表，每一列是一个字段，每一行是一条记录。在Python2中连接MySql的库大多是MySQLdb，但是这个库在Python3中不在支持，所以这里我推荐是PyMySQL。相信PyMySQL的安装大家都懂，只需要pip install pymysql下载">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://ws1.sinaimg.cn/large/006bO2RVly1fywxpx0ffqj30r10iq42f.jpg">
<meta property="og:updated_time" content="2019-01-26T11:49:50.572Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MySql数据库操作">
<meta name="twitter:description" content="MySql数据库的基本操作 MySql是关系型数据，关系型数据库是基于关系模型的数据库，而关系模型是通过二维表来保存的，所以它的存储方式就是行列组成的表，每一列是一个字段，每一行是一条记录。在Python2中连接MySql的库大多是MySQLdb，但是这个库在Python3中不在支持，所以这里我推荐是PyMySQL。相信PyMySQL的安装大家都懂，只需要pip install pymysql下载">
<meta name="twitter:image" content="https://ws1.sinaimg.cn/large/006bO2RVly1fywxpx0ffqj30r10iq42f.jpg">



  <link rel="alternate" href="/atom.xml" title="LF's Blogs" type="application/atom+xml">




  <link rel="canonical" href="http://yoursite.com/2018/12/07/MySql数据库操作/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>MySql数据库操作 | LF's Blogs</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">LF's Blogs</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">Hungry For Studying...</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-search">

    
    
    
      
    

    

    <a href="/search/" rel="section"><i class="menu-item-icon fa fa-fw fa-search"></i> <br>搜索</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/12/07/MySql数据库操作/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Light Fish">
      <meta itemprop="description" content="Hungry For Studying...">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LF's Blogs">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MySql数据库操作

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-12-07 18:04:11" itemprop="dateCreated datePublished" datetime="2018-12-07T18:04:11+08:00">2018-12-07</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-01-26 19:49:50" itemprop="dateModified" datetime="2019-01-26T19:49:50+08:00">2019-01-26</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          <span class="post-meta-divider">|</span>
<span title="post.wordcount"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i></span>字数： 1.2k</span>

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="MySql数据库的基本操作"><a href="#MySql数据库的基本操作" class="headerlink" title="MySql数据库的基本操作"></a>MySql数据库的基本操作</h1><blockquote>
<p>MySql是关系型数据，关系型数据库是基于关系模型的数据库，而关系模型是通过二维表来保存的，所以它的存储方式就是行列组成的表，每一列是一个字段，每一行是一条记录。<br><br><br>在Python2中连接MySql的库大多是MySQLdb，但是这个库在Python3中不在支持，所以这里我推荐是PyMySQL。相信PyMySQL的安装大家都懂，只需要<code>pip install pymysql</code>下载到本地，然后安装，这里就不详述了。=.=</p>
</blockquote>
<a id="more"></a>
<h3 id="1-数据库的连接等简单操作"><a href="#1-数据库的连接等简单操作" class="headerlink" title="1.数据库的连接等简单操作"></a>1.数据库的连接等简单操作</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">import pymysql</span><br><span class="line"></span><br><span class="line">db = pymysql.connect(</span><br><span class="line">    host=&apos;localhost&apos;, #本地就是localhost或者127.0.0.1</span><br><span class="line">    user=&apos;root&apos;, #你的MySql登录用户名</span><br><span class="line">    password=&apos;&apos;, #登录密码</span><br><span class="line">    port=3306  #默认端口是3306</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>
<blockquote>
<p>取数据库的游标</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">cursor = db.cursor()</span><br><span class="line">cursor.execute(&apos;SELECT VERSION()&apos;) #查看数据库的版本号 注意execute就是执行mysql语句</span><br></pre></td></tr></table></figure>
<blockquote>
<p>取数据库的版本</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">data = cursor.fetchone() #fetchone()就是获取第一条数据，也就是上面的那个版本号</span><br><span class="line">print(&apos;Database version:&apos; + data[0])</span><br></pre></td></tr></table></figure>
<blockquote>
<p>建了一个名为spider 的数据库，并且默认编码是utf-8</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cursor.execute(&apos;CREATE DATABASE spider DEFAULT CHARACTER SET utf8&apos;) #default character set utf8 注意没有&apos;-&apos;哦</span><br></pre></td></tr></table></figure>
<blockquote>
<p>选中数据库</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cursor.execute(&apos;USE spider&apos;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>建表</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sql = &apos;CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL,name VARCHAR(25)NOT NULL,age INT NOT NULL,PRIMARY KEY (id))&apos;</span><br><span class="line">cursor.execute(sql)</span><br></pre></td></tr></table></figure>
<p>这里就是成功截图</p>
<p><img src="https://ws1.sinaimg.cn/large/006bO2RVly1fywxpx0ffqj30r10iq42f.jpg" alt="img"></p>
<p>emmm，我用的是mysql的一个可视化工具<code>navicat</code>,你可以到这来<a href="https://pan.baidu.com/s/13BDqu8idklKPbYO1HPO5TQ" target="_blank" rel="noopener">下载</a> 密码: 5w3y<br>下面就是真正的mysql基本操作了</p>
<h3 id="2-插入数据"><a href="#2-插入数据" class="headerlink" title="2.插入数据"></a>2.插入数据</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">id = &apos;2016210405068&apos;</span><br><span class="line">name = &apos;言语&apos;</span><br><span class="line">age = 18</span><br><span class="line">sql = &apos;INSERT INTO students(id,name,age) values(%s,%s,%s)&apos; #sql语句</span><br></pre></td></tr></table></figure>
<blockquote>
<p>插入数据的标准写法</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">try:</span><br><span class="line">    cursor.execute(sql, (id, name, age))</span><br><span class="line">    # 需要执行db对象的commit()方法才能实现数据的插入，对于数据的插入、更新、删除操作都需要调用</span><br><span class="line">    print(&apos;Sucessful insert...&apos;)</span><br><span class="line">    db.commit()</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(e)</span><br><span class="line">    # 加了一层异常处理，如果执行失败，则调用rollback()函数来执行数据的回滚，相当于什么都没有发生</span><br><span class="line">    db.rollback()</span><br></pre></td></tr></table></figure>
<blockquote>
<p><strong>注意</strong> 在很多情况下我们要达到的效果是插入方法无需改动，只需要传入一个字典就行，比如构造这个字典：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">data = &#123;</span><br><span class="line">    &apos;id&apos;: &apos;2016210405068&apos;,</span><br><span class="line">    &apos;name&apos;: &apos;lightfish&apos;,</span><br><span class="line">    &apos;age&apos;: 22</span><br><span class="line">&#125;</span><br><span class="line">table = &apos;students&apos; #数据库表</span><br><span class="line">keys = &apos;,&apos;.join(data.keys())  # str类型</span><br><span class="line">values = &apos;,&apos;.join([&apos;%s&apos;] * len(data))</span><br><span class="line">sql = &apos;INSERT INTO &#123;table&#125;(&#123;key&#125;) VALUES(&#123;values&#125;)&apos;.format(table=table, key=keys, values=values)</span><br><span class="line">try:</span><br><span class="line">    if cursor.execute(sql, tuple(data.values)): #元组类型</span><br><span class="line">        print(&apos;Sucessful insert&apos;)</span><br><span class="line">        db.commit</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(e)</span><br><span class="line">    db.rollback()</span><br></pre></td></tr></table></figure>
<h3 id="更改数据"><a href="#更改数据" class="headerlink" title="更改数据"></a>更改数据</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">sql = &apos;UPDATE students SET age=%s WHERE name=%s&apos;</span><br><span class="line">try:</span><br><span class="line">    cursor.execute(sql, (22, &apos;Bob&apos;))</span><br><span class="line">    db.commit()</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(e)</span><br><span class="line">    db.rollback()</span><br></pre></td></tr></table></figure>
<blockquote>
<h4 id="注意-下面这个很重要"><a href="#注意-下面这个很重要" class="headerlink" title="注意 下面这个很重要"></a><strong>注意</strong> 下面这个很重要</h4></blockquote>
<blockquote>
<p>更新数据的时候，我们关心会不会出现重复的问题。所以我们这里可以再实现一种去重的方法，如果数据存在，则更新数据；否则插入数据</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">data = &#123;</span><br><span class="line">    &apos;id&apos;: &apos;2016210405068&apos;,</span><br><span class="line">    &apos;name&apos;: &apos;辰东&apos;,</span><br><span class="line">    &apos;age&apos;: 33</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">table = &apos;students&apos;</span><br><span class="line">keys = &apos;,&apos;.join(data.keys())</span><br><span class="line">values = &apos;,&apos;.join([&apos;%s&apos;] * len(data))</span><br><span class="line"></span><br><span class="line"># on duplicate key update</span><br><span class="line"></span><br><span class="line">sql = &apos;INSERT INTO &#123;table&#125;(&#123;keys&#125;) VALUES (&#123;values&#125;) ON DUPLICATE KEY UPDATE&apos;.format(table=table, keys=keys,</span><br><span class="line">                                                                                     values=values)</span><br><span class="line">update = &apos;,&apos;.join([&apos; &#123;key&#125;=%s&apos;.format(key=key) for key in data.keys()])</span><br><span class="line">sql += update</span><br><span class="line"></span><br><span class="line">try:</span><br><span class="line">    cursor.execute(sql, tuple(data.values()) * 2)</span><br><span class="line">    print(&apos;Sucessfull insert...&apos;)</span><br><span class="line">    db.commit()</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(e)</span><br><span class="line">    db.rollback()</span><br></pre></td></tr></table></figure>
<blockquote>
<p>完整的SQL语句是<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">INSERT INTO students(id, name, age) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE id = %s, name = %s, age = %s</span><br></pre></td></tr></table></figure></p>
</blockquote>
<h3 id="删除数据"><a href="#删除数据" class="headerlink" title="删除数据"></a>删除数据</h3><blockquote>
<p>删除数据就相对简单了直接用<code>DELETE</code>，但是依然要用<code>commit()</code>函数才能生效</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">table = &apos;students&apos;</span><br><span class="line">conditions = &apos;age&gt;20&apos;</span><br><span class="line">sql = &apos;DELETE FROM &#123;table&#125; WHERE &#123;condition&#125;&apos;.format(table=table, condition=conditions)</span><br><span class="line">try:</span><br><span class="line">    cursor.execute(sql)</span><br><span class="line">    print(&apos;Delete sucessfull...&apos;)</span><br><span class="line">    db.commit()</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(e)</span><br><span class="line">    db.rollback()</span><br></pre></td></tr></table></figure>
<h3 id="查询数据库"><a href="#查询数据库" class="headerlink" title="查询数据库"></a>查询数据库</h3><blockquote>
<p><strong>注意</strong><code>fetch</code>方法内部实现有一个偏移，开始的<code>fetchone()</code>就获取了一条数据，所以后面的<code>fetchall()</code>只获取了总数减一条，因此我推荐后面一种方法，用<code>while</code>方法加<code>fetchone()</code>,<code>fetchall()</code>会将结果以元组的形式全部返回，如果数据很大就占用的开销很大。</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">try:</span><br><span class="line">    cursor.execute(sql)</span><br><span class="line">    print(&apos;Counts: &apos;+cursor.rowcount)</span><br><span class="line">    one = cursor.fetchone()</span><br><span class="line">    print(&apos;One: &apos;+one)</span><br><span class="line">    results = cursor.fetchall()</span><br><span class="line">    print(&apos;Results: &apos;+results)</span><br><span class="line">    print(&apos;The type of results: &apos;+type(results))</span><br><span class="line">    for row in results:</span><br><span class="line">        print(row)</span><br><span class="line">except Exception as e:</span><br><span class="line">    print(e)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>第二种方法</p>
</blockquote>
<pre><code>try:
    cursor.execute(sql)
    print(&apos;Counts: &apos;+cursor.rowcount)
    one = cursor.fetchone() #one是一个元组
    while one:
        print(&apos;Row: &apos;,one)
        one = cursor.fetchone()
except Exception as e:
    print(e)
</code></pre><p><br><br><br><br>以上就是Mysql的基本操作，So<br><br>Just have fun…</p>

      
    </div>



    

    
    
    

    <div>
      
      <div>

    <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>

</div>
      
    </div>

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MySql/" rel="tag"># MySql</a>
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/12/07/MongoDB数据库基本操作/" rel="next" title="MongoDB数据库基本操作">
                <i class="fa fa-chevron-left"></i> MongoDB数据库基本操作
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/12/11/rdcloud词云/" rel="prev" title="wordcloud词云">
                wordcloud词云 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Light Fish">
            
              <p class="site-author-name" itemprop="name">Light Fish</p>
              <p class="site-description motion-element" itemprop="description">Hungry For Studying...</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">35</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">13</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">22</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/QGtiger" title="GitHub &rarr; https://github.com/QGtiger" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://weibo.com/yourname" title="Weibo &rarr; https://weibo.com/yourname" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/yourname" title="Twitter &rarr; https://twitter.com/yourname" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#MySql数据库的基本操作"><span class="nav-number">1.</span> <span class="nav-text">MySql数据库的基本操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-数据库的连接等简单操作"><span class="nav-number">1.0.1.</span> <span class="nav-text">1.数据库的连接等简单操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-插入数据"><span class="nav-number">1.0.2.</span> <span class="nav-text">2.插入数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#更改数据"><span class="nav-number">1.0.3.</span> <span class="nav-text">更改数据</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#注意-下面这个很重要"><span class="nav-number">1.0.3.1.</span> <span class="nav-text">注意 下面这个很重要</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除数据"><span class="nav-number">1.0.4.</span> <span class="nav-text">删除数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询数据库"><span class="nav-number">1.0.5.</span> <span class="nav-text">查询数据库</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Light Fish</span>

  

  
</div>


<!-- 新增访客统计代码 -->

<div class="busuanzi-count">
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="site-uv">
      <i class="fa fa-user"></i>
      访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv"></span> 人
    </span>
    <div class="powered-by"></div>
    <span class="site-uv">
      <i class="fa fa-eye"></i>
      访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv"></span> 次
    </span>
    <!-- 博客字数统计 -->
    <span class="site-pv">
      <i class="fa fa-pencil"></i>
      博客全站共： <span class="post-count">31.7k</span> 字
    </span>
</div>
<!-- 新增访客统计代码 END-->

<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>  
<script>
    var now = new Date(); 
    function createtime() { 
        var grt= new Date("12/03/2018 12:49:00");//此处修改你的建站时间或者网站上线时间 
        now.setTime(now.getTime()+250); 
        days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days); 
        hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours); 
        if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum); 
        mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;} 
        seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum); 
        snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;} 
        document.getElementById("timeDate").innerHTML = "本站已安全运行 "+dnum+" 天 "; 
        document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒"; 
    } 
setInterval("createtime()",250);
</script>
        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=6.7.0"></script>

  <script src="/js/src/motion.js?v=6.7.0"></script>



  
  


  <script src="/js/src/schemes/muse.js?v=6.7.0"></script>



  
  <script src="/js/src/scrollspy.js?v=6.7.0"></script>
<script src="/js/src/post-details.js?v=6.7.0"></script>



  


  <script src="/js/src/bootstrap.js?v=6.7.0"></script>



  


  


  

  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

  

  

  

  

  

  

  

</body>
</html>
